import fs from "fs-extra";
import { TaskResult } from "../../common/tasks/BastTask.js";
import { BuildUnityResult, WebGLBuildUnityBaseTask } from "./WebGLBuildUnityBaseTask.js";
import { WebGLEnv } from "../WebGLEnv.js";
import path from "path";
import { toolchain } from "../../toolchain.js";
import { eitherPath } from "../../tools/vendor.js";
import { convertToUnicode } from "../../tools/unicode.js";
import { CommonEnv } from "../../common/CommonEnv.js";
import { WechatTools } from "../../tools/WechatTools.js";
import { Nullable } from "../../typings.js";
import { CheckEnvTask } from "../../common/tasks/CheckEnvTask.js";

export class WebGLBuildMiniGameTask extends WebGLBuildUnityBaseTask {
    async run(): Promise<TaskResult<BuildUnityResult>> {
        // 修改的转换配置
        const mgCfg = eitherPath(path.join(toolchain.params.workSpacePath, WebGLEnv.MiniGameConfigAsset), path.join(toolchain.params.workSpacePath, WebGLEnv.MiniGameConfigAssetV2));
        const mgCfgContent = await fs.readFile(mgCfg, 'utf-8');

        // 修改CDN
        const cdnURL = toolchain.unity.getCDNURL();
        let newContent = mgCfgContent.replace(/(?<=CDN: ).+/, cdnURL);

        // 修改appid和包名
        newContent = newContent.replace(/(?<=Appid: ).+/, toolchain.params.channelCfg.wx!.appid);
        const pn = convertToUnicode(toolchain.params.channelCfg.productName);
        newContent = newContent.replace(/(?<=projectName: ").+?(?=")/, pn);

        // 修改导出目录
        const exportRoot = path.join(toolchain.params.workSpacePath, WebGLEnv.ExportMiniGameRoot);
        newContent = newContent.replace(/(?<=DST: ).+/, exportRoot.replaceAll(path.sep, '/'));

        // 开发版打开调试选项
        if (toolchain.params.channelCfg.defines.includes('DEVELOP')) {
            newContent = newContent.replace('profilingFuncs: 0', 'profilingFuncs: 1');
        }

        console.log('minigame setting:');
        console.log('---------------------');
        console.log(newContent);
        console.log('---------------------');

        await fs.writeFile(mgCfg, newContent, 'utf-8');

        // 先关闭开发者工具，否则可能提示EBUSY
        await WechatTools.quit(path.join(exportRoot, WebGLEnv.MiniGameRoot));
        
        // 通过微信提供的webgl转化项目进行WebGL Build
        const result = await this.callUnity(WebGLEnv.ExportMiniGameRoot, 'BuildForMiniGame');
        if (!result.success) return result;

        // 写入appVer.txt记录application版本，以供手动上传时使用
        const verTxt = path.join(toolchain.params.workSpacePath, CommonEnv.VersionCodeTxt);
        const mainVer = await fs.readFile(verTxt, 'utf-8');
        const appVerFile = path.join(toolchain.params.workSpacePath, WebGLEnv.MiniGameAppVerFile);
        await fs.writeFile(appVerFile, `${toolchain.params.version}.${mainVer}`, 'utf-8');

        // 将小游戏资源拷贝到cdn
        const cdn = path.join(toolchain.params.uploadPath, WebGLEnv.MiniGameAssetRoot);
        await fs.copy(path.join(exportRoot, WebGLEnv.WebglRoot), cdn);
        // iOS下请跟随该指引申请高性能模式，即wkwebview模式。开了该模式才有JIT以及WeakRef

        return result;
    }

    get dependencies(): Nullable<string[]> {
        const superDepends = super.dependencies;
        return (superDepends ?? []).concat([CheckEnvTask.name]);
    }
}
